import http from './http';

// 登录API
export const login = async (username, password) => {
  try {
    const response = await http.post('/auth/login', { username, password });
    if (response.success) {
      // 保存JWT令牌到sessionStorage
      sessionStorage.setItem('token', response.data.token);
      sessionStorage.setItem('user', JSON.stringify({
        id: response.data.id,
        username: response.data.username,
        email: response.data.email,
        role: response.data.role
      }));
    }
    return response;
  } catch (error) {
    console.error('登录错误:', error);
    return {
      success: false,
      message: error.message || '登录失败，请检查用户名和密码'
    };
  }
};

// 注册API
export const register = async (userData) => {
  try {
    const response = await http.post('/auth/register', userData);
    return response;
  } catch (error) {
    console.error('注册错误:', error);
    return {
      success: false,
      message: error.message || '注册失败，请稍后再试'
    };
  }
};

// 退出登录
export const logout = () => {
  sessionStorage.removeItem('token');
  sessionStorage.removeItem('user');
};

// 获取当前用户信息
export const getCurrentUser = () => {
  const userStr = sessionStorage.getItem('user');
  return userStr ? JSON.parse(userStr) : null;
};

// 设置当前用户信息
export const setCurrentUser = (user) => {
  sessionStorage.setItem('user', JSON.stringify(user));
};

// 检查用户是否已登录
export const isAuthenticated = () => {
  return !!sessionStorage.getItem('token');
};

// 检查用户是否为管理员
export const isAdmin = () => {
  const user = getCurrentUser();
  return user && user.role === 'ADMIN';
}; 